/*
 * @(#)ValidationInterceptor.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.interceptor.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorResult;
import org.apache.commons.validator.ValidatorResults;

import com.nhncorp.lucy.web.interceptor.AbstractInterceptor;
import com.nhncorp.usf.core.config.runtime.Action;
import com.nhncorp.usf.core.config.runtime.PageInfo;
import com.nhncorp.usf.core.xwork.ActionInvocationHelper;
import com.nhncorp.usf.core.xwork.DefaultUsfActionInvocation;
import com.opensymphony.xwork.ActionInvocation;

/**
 * validation을 처리하는 Interceptor
 * <p/>
 *
 * @author Web Platform Development Team
 */
public class ValidationInterceptor extends AbstractInterceptor implements InterceptorPropertyAware {
    private static final long serialVersionUID = -4240281219838251349L;
    private Properties properties;
    private static final String FAILED_CODE_VALIDATION = "validationFail";

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Properties getProperties() {
        return properties;
    }

    /**
     * @param invocation the ActionInvocation
     * @return the interceptor result
     * @throws Exception for Exception
     */
    @SuppressWarnings("unchecked")
    public String intercept(ActionInvocation invocation) throws Exception {
        String id = ((Action)((DefaultUsfActionInvocation) invocation).getActionInfo()).getId(); //action의 이름을 저장
        PageInfo pageInfo = ((DefaultUsfActionInvocation) invocation).getPageInfo();
        Validator validator = pageInfo.getValidator(id);
        
        if (validator == null) {
        	return invocation.invoke();
        }
        
        // Validator validator = new Validator(resources, id);
        // 사용자 입력 파라미터
        Map<String, Object> dataMap = (Map<String, Object>) ActionInvocationHelper.getDataMap(invocation);
        validator.setParameter(Validator.BEAN_PARAM, dataMap);
        ValidatorResults validatorResults = validator.validate();

        Map<String, String> invalidResult = new HashMap<String, String>(); // validation 에 실패한 field들의 정보를 갖고있는 map

        Iterator iterFieldNames = validatorResults.getPropertyNames().iterator(); // fieldName의 set

        while (iterFieldNames.hasNext()) {
            String fieldName = (String) iterFieldNames.next();
            ValidatorResult validatorResult = validatorResults.getValidatorResult(fieldName);

            Iterator itervalidatorName = validatorResult.getActions(); // field 에 설정된 validator set
            String invalidValidatorName = null;            // invalid된 validator를 저장

            while (itervalidatorName.hasNext()) { // field 각각에 대한 validation 의 결과  검사
                String validatorName = (String) itervalidatorName.next();

                if (validatorResult.isValid(validatorName) == false) {
                    invalidValidatorName = validatorName;
                }
            }

            if (invalidValidatorName != null) {
                invalidResult.put(fieldName, invalidValidatorName);
            }

        }
        if (!invalidResult.isEmpty()) {
            dataMap.put("validatorResults", invalidResult);
            return FAILED_CODE_VALIDATION;
        }

        return invocation.invoke();
    }
}
